package com.idealighter.game.web.recharge.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import com.idealighter.game.recharge.constant.AliPayConstant;
import com.idealighter.game.web.recharge.service.PayService;
import com.idealighter.utils.check.EmptyUtil;
import com.idealighter.utils.wepay.core.Wepay;
import com.idealighter.utils.wepay.util.SimpleXmlMaps;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;

import org.jboss.resteasy.spi.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// import com.abgame.usersystem.sts.sample.StsServiceSample;


@Path("/pay")
@Singleton
public class PayController {
  private static final Logger logger = LoggerFactory.getLogger(PayController.class);
  @Inject
  private PayService payService;
  @Inject
  private Wepay wepay;

  /**
   * 支付通知.
   * 
   * @Title notify.
   * @param request 请求内容
   * @return 处理结果
   */
  @Path("/we_chat_notify")
  @POST
  @Produces("text/plain; charset=utf-8")
  public String notify(
      @Context final HttpRequest request /* @Context . HttpServletRequest request */) {
    String notifyXml = getPostRequestBody(request);
    logger.info("notifyXml: " + notifyXml);
    String result = wepay.notifies().notOk("fail");
    if (EmptyUtil.stringIsNotEmpty(notifyXml)) {
      Map<String, String> notifyParams = SimpleXmlMaps.toMap(notifyXml);
      // 校验签名
      if (wepay.notifies().verifySign(notifyParams)) {
        // 处理业务
        boolean sign = payService.weChatPayNotify(notifyParams);
        if (sign == true) {
          result = wepay.notifies().ok();
        } else {
          result = wepay.notifies().notOk("执行失败");
        }
      } else {
        result = wepay.notifies().notOk("签名失败");
      }
    } else {
      result = wepay.notifies().notOk("body为空");
    }
    return result;
  }

  /**
   * 支付宝支付回调.
   * 
   * @Title ali_notify.
   */
  @Path("/ali_notify")
  @POST
  @Produces("text/plain; charset=utf-8")
  public String ali_notify(@Context final HttpRequest request)
      throws AlipayApiException, UnsupportedEncodingException {
    MultivaluedMap<String, String> requestParams = request.getFormParameters();
    // Map<String, String[]> requestParams = request.getParameterMap();
    Map<String, String> params = new HashMap<String, String>();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
      String name = iter.next();
      List<String> values = requestParams.get(name);
      String valueStr = "";
      if (values != null) {
        for (int i = 0; i < values.size(); i++) {
          String value = URLDecoder.decode(values.get(i), "utf-8");
          valueStr = (i == values.size() - 1) ? valueStr + value : valueStr + value + ",";
        }
      }
      params.put(name, valueStr);
    }
    boolean flag =
        AlipaySignature.rsaCheckV1(params, AliPayConstant.ALI_PUBLIC_Key, "utf-8", "RSA2");
    String result = "false";
    if (flag) {
      boolean sign = payService.aliPayNotify(params);
      if (sign) {
        result = "success";
      }
    }
    return result;
  }

  private String getPostRequestBody(HttpRequest req) {
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;
    try {
      InputStream inputStream = req.getInputStream();
      if (inputStream != null) {
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        char[] charBuffer = new char[128];
        int bytesRead = -1;
        while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
          stringBuilder.append(charBuffer, 0, bytesRead);
        }
      } else {
        stringBuilder.append("");
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
    return stringBuilder.toString();
  }

  // private String getPostRequestBody(HttpServletRequest req) {
  // if (req.getMethod().equals("POST")) {
  // StringBuilder sb = new StringBuilder();
  // try (BufferedReader br = req.getReader()) {
  // char[] charBuffer = new char[128];
  // int bytesRead;
  // while ((bytesRead = br.read(charBuffer)) != -1) {
  // sb.append(charBuffer, 0, bytesRead);
  // }
  // } catch (IOException e) {
  // logger.warn("failed to read request body, cause: ", e);
  // }
  // return sb.toString();
  // }
  // return "";
  // }
}
